package com.tech.service.impl;

import com.tech.mapper.GoodsDao;
import com.tech.mapper.GoodsImageDao;
import com.tech.mapper.factory.DaoImplFactory;
import com.tech.repository.dto.GoodsInfo;
import com.tech.repository.entity.Goods;
import com.tech.service.GoodsImageService;
import com.tech.service.GoodsService;
import com.tech.view.common.ResourcesUtil;
import com.tech.view.panel.GoodsCardPanel;

import java.util.List;
import java.util.stream.Collectors;

public class GoodsServiceImpl implements GoodsService {

	private GoodsDao goodsDao = DaoImplFactory.getGoodsDao();
	private GoodsImageDao goodsImageDao = DaoImplFactory.getGoodsImageDao();
	private GoodsImageService goodsImageService = ServiceImplFactory.getGoodsImageService();

	@Override
	public List<GoodsInfo> getRecommendGoods(int beginIndex, int count) {
		List<Goods> goods = goodsDao.getGoodsList(beginIndex, count, "gpopularity desc");

		// 商品图片暂时先不获取
		List<GoodsInfo> goodsInfos = goods.stream()
				.map(g -> new GoodsInfo(g, goodsImageDao.getGoodsImageIgnoreImage(g.getGid())))
				.toList();

		// 获取第一张商品图片
		goodsInfos.forEach(goodsInfo -> goodsImageService.getImage(goodsInfo.getImages(), 1,
				GoodsCardPanel.DEFAULT_WIDTH, ResourcesUtil.CacheDir.GOODS_CARD.getDir()));

		return goodsInfos;
	}

	@Override
	public List<GoodsInfo> getGoodsList(int beginIndex, int count, int imageCount, String order) {
		List<Goods> goods = goodsDao.getGoodsList(beginIndex, count, order);
		return goods.stream()
				.map(g -> new GoodsInfo(g, goodsImageDao.getGoodsImagesList(g.getGid(), imageCount)))
				.collect(Collectors.toList());
	}

	@Override
	public List<Goods> getByKeyword(String keyword) {
		return null;
	}

	@Override
	public int addGoods(Goods goods) {
		return goodsDao.addGoods(goods);
	}

	@Override
	public boolean delGoods(Integer gid) {
		return goodsDao.delGoods(gid);
	}

	@Override
	public boolean updateGoods(Goods editedGoods) {
		return goodsDao.updateGoods(editedGoods);
	}
}
